#!/usr/bin/env python
#encoding=utf8
"""
@描述：职能三级标签的json格式
@日期：2015年01月29日 星期四

@作者：hongxingfan
"""

import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding("utf8")

def openConn():
	conn = MySQLdb.connect(host="192.168.1.251",user="root",passwd="",db="jobs",charset="utf8")
	return conn

class JobClass:
	def __init__(self,id,name):
		self.id = id
		self.name = name
	def __str__(self):
		print("id=%d,name=%s" %(self.id,self.name))
	def __eq__(self, oth):
		return self.id == oth.id and self.name == oth.name
	def __hash__(self):
		return hash(str(self.id) + "\t" + self.name)
	# 重载__cmp__函数
	def __cmp__(self,oth):
		return cmp(self.name,oth.name)

if __name__ == "__main__":
	conn = openConn()
	select = """
		SELECT firstId,firstName,secondId,secondName,thirdId,thirdName FROM jobclass_tag 
		ORDER BY firstName ASC,secondName ASC,thirdName ASC 
	"""
	cur = conn.cursor()
	cur.execute(select)
	result = cur.fetchall()

	firstKey = None
	secondKey = None
	# 采用list结构加以完善
	jsonMap = dict()
	#print("\"industry_1\":[")
	for (firstId,firstName,secondId,secondName,thirdId,thirdName) in result:
		f = JobClass(firstId,firstName)
		s = JobClass(secondId,secondName)
		t = JobClass(thirdId,thirdName)
		if(f in jsonMap):
			ss = jsonMap.get(f)
			if(s in ss):
				ss.get(s).append(t)
			else:
				ss[s] = [t]
		else:
			m = dict()
			m[s] = [t]
			jsonMap[f] = m
	#print("\"jobclass\":[")
	content = []
	content.append("\"jobclass\":[")
	#  排序的map，确保行业标签的优先级;items()后变成[(),()...]结构
	for (f,v) in sorted(jsonMap.iteritems(),key=lambda x:x[0].name):
		content.append("{\"code\":%d," %(f.id))
		#print("{\"code\":%d," %(f.id))
		content.append("\"name\":\"%s\"," %(f.name))
		#print("\"name\":\"%s\"," %(f.name))
		content.append("\"child\":[")
		#print("\"second\":[")
		for (s,vv) in v.items():
			content.append("{\"code\":%d," %(s.id))
			#print("{\"code\":%d," %(s.id))
			content.append("\"name\":\"%s\"," %(s.name))
			#print("\"name\":\"%s\"," %(s.name))
			content.append("\"child\":[")
			#print("\"third\":[")
			for vvv in vv:
				content.append("{\"code\":%d," %(vvv.id))
				#print("{\"code\":%d," %(vvv.id))
				content.append("\"name\":\"%s\"}" %(vvv.name))
				content.append(",")
				#print("\"name\":\"%s\"}," %(vvv.name))
			content.pop()
			#print("]},")
			content.append("]}")
			content.append(",")
		content.pop()
		#print("]},")
		content.append("]}")
		content.append(",")
	content.pop()
	content.append("]")
	#print("]")
	for c in content:
		print(c)
	conn.close()
